#include <libdswutility/dswrtcctrl.h>
#include <linux/rtc.h>

#define RTC_DEV_NAME "/dev/rtc"

CDswrtcctrl::CDswrtcctrl(LPST_ENV_T pEnv)
: CDswbase(pEnv)
, m_nRtcfd(-1)
{
	m_nRtcfd = open(RTC_DEV_NAME, O_RDONLY|O_NONBLOCK);
	if (m_nRtcfd == -1)
		LOG4CPLUS_ERROR(log_dsw, "Open [ " << RTC_DEV_NAME << " ] failed!");
	LOG4CPLUS_DEBUG(log_dsw, "Create CDswrtcctrl class!");
}

CDswrtcctrl::~CDswrtcctrl()
{
	if (m_nRtcfd != -1)
		close(m_nRtcfd);
	LOG4CPLUS_DEBUG(log_dsw, "Destroy CDswrtcctrl class!");
}

int CDswrtcctrl::OnMessage(EN_MSG_TYPE nMsgType, void * pParam)
{
	if (m_nRtcfd == -1)
		return 0;
	struct rtc_time tm;
	switch(nMsgType){
	case PMSG_SET_RTCTIME:
		{
			sscanf((char*)pParam, "%d-%d-%d %d:%d:%d", &tm.tm_year,
				&tm.tm_mon, &tm.tm_mday,&tm.tm_hour,
				&tm.tm_min, &tm.tm_sec);
			tm.tm_isdst = 0;
			tm.tm_year -= 1900;
			tm.tm_mon -= 1;
			int nRet = ioctl(m_nRtcfd, RTC_SET_TIME, &tm);
			if (nRet != 0)
				LOG4CPLUS_ERROR(log_dsw, "Set RTC error! err = " << strerror(errno));
		}
		break;
	case PMSG_GET_RTCTIME:
		{
			int nRet = ioctl(m_nRtcfd, RTC_RD_TIME, &tm);
			if (nRet != 0){
				*((char*)pParam) = '\0';
				LOG4CPLUS_ERROR(log_dsw, "Get RTC error! err = " << strerror(errno));
			}
			else{
				sprintf((char*)pParam, "%04-%02-%02 %02:%02:%02", tm.tm_year + 1900,
					tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
			}
		}
		break;
	}
	return 0;
}

